﻿using System;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Windows;
using Betfair.Api;
using Bull.Core;
using Bull.Plugins.Login.ViewModels;
using Bull.Plugins.Login.Views;
using Bull.UI.Properties;
using Bull.UI.ViewModels;
using Bull.UI.Views;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace Bull.UI {
    public partial class App {
        protected override void OnStartup(StartupEventArgs e) {
            base.OnStartup(e);
            var container = new UnityContainer().LoadConfiguration();
            
            IoC.Container.SetBetfairProxy(container.Resolve<IBetfairProxy>());
            IoC.Container.SetScheduler(container.Resolve<IScheduler>());

            var loginView = new LoginView();
            var loginViewModel = new LoginViewModel(
                UserSettings.Default.Username,
                UserSettings.Default.ApplicationKey,
                UserSettings.Default.CertificatePath,
                container.Resolve<IOpenFileDialog>()
            );
            loginViewModel.OnLogin()
                .Select(item => item)
                .Subscribe(result => {
                    loginView.Hide();
                    var mainView = new MainView {
                        DataContext = new MainViewModel()
                    };
                    Close(loginViewModel, loginView, mainView);
                    mainView.Show();
                });
            loginView.DataContext = loginViewModel;
            loginView.Show();
        }

        private static void Close(LoginViewModel loginViewModel, Window loginView, Window mainView) {
            Observable.FromEventPattern<EventHandler, EventArgs>(handler =>
                mainView.Closed += handler,
                    handler => mainView.Closed -= handler).Subscribe(closed => {
                        UserSettings.Default.Username = loginViewModel.Username;
                        UserSettings.Default.ApplicationKey = loginViewModel.ApplicationKey;
                        UserSettings.Default.CertificatePath = loginViewModel.CertificatePath;
                        UserSettings.Default.Save();
                        loginView.Close();
                        Environment.Exit(0);
                    });
        }
    }
}
